
L.TaskList = L.Class.extend({
  includes: L.Mixin.Events,
  
  initialize: function(taskListId){
    this._taskListId = taskListId;
    this._tasks = [];
    this._sendToServer = true;
//    this.useAdapter(L.clientAdapter);
  },

  sendToServer: function(bool){
    this._sendToServer = bool;
  },

  addTask: function(id, name, roomId){
    var task = {
      id:id,
      name:name,
      roomId:roomId
    };

    this._tasks.push(task);

    if(this._sendToServer){
      this.sendEvent({
          operation: "addTask",
          id: id,
          name: name,
          roomId:roomId
      });
    }

    this.fire('addTask', task);
  
  },

  eachTask: function(fn, context){
    var tasks = this._tasks;
    for(var key in tasks){
      if(tasks.hasOwnProperty(key)){
        fn.call(context, tasks[key]);
      }
    }
  },
  
  getTask: function(id){
    var tasks = this._tasks;
    for(var i=0, n=tasks.length; i<n; i++){
      if(tasks[i].id === id){
        return tasks[i];
      }
    }
    return null;
  },

  getTasks: function(){
    return this._tasks;
  },

  getCount: function(){
    return this._tasks.length;
  },

  useAdapter: function(clientAdapter){
      var self = this;
      var taskListId = this._taskListId;

      var handler = new Handler(clientAdapter, {
        objectId: taskListId,
        type: "EVENT",
        echo: false,
        receiveEvent: function(object, c){
          self.sendToServer(false);
          switch(c.operation){
            case "addTask":
              self.addTask(c.id, c.name, c.roomId);
              break;
            default:
              console.log("[WARNING] User.useAdapter: operacion no soportada: " + c.operation);
          }
          self.sendToServer(true);
        },
        setState: function(object, content){
          this._tasks = content;
        }
      });

      this.sendEvent = function(content){
        handler.sendEvent(taskListId, content);  
      }
      
      clientAdapter.couple(taskListId, handler);

  },


});
